layui.use(['layer','element'], function(){
    var layer = layui.layer,element = layui.element;
    initUser();
    loadMenu();
    //建立连接
    connectionSocket();
    $('#signOut').click(function () {
        confirm_inquiry('您是否确定要退出？',function () {
            show_loading();$.post(rurl('scm/auth/logout'),{},function () {setLocalStorage('TSF_SCM','');setLocalStorage('TSF_SCM_U','');toUrl('login.html')});
        });
    });
    $('.full-screen').click(function () {
       var $that = $(this);
       if($that.attr('full')=='false'){
           var elem = document.body;
           if (elem.webkitRequestFullScreen) {
               elem.webkitRequestFullScreen();
           } else if (elem.mozRequestFullScreen) {
               elem.mozRequestFullScreen();
           } else if (elem.requestFullScreen) {
               elem.requestFullscreen();
           } else {
               show_msg("浏览器不支持全屏API或已被禁用");
               return;
           }
           $that.attr({'full':true,'title':'退出全屏'}).html('<i class="layui-icon layui-icon-screen-restore"></i>');
       }else{
           var elem = document;
           if (elem.webkitCancelFullScreen) {
               elem.webkitCancelFullScreen();
           } else if (elem.mozCancelFullScreen) {
               elem.mozCancelFullScreen();
           } else if (elem.cancelFullScreen) {
               elem.cancelFullScreen();
           } else if (elem.exitFullscreen) {
               elem.exitFullscreen();
           } else {
               show_msg("浏览器不支持全屏API或已被禁用");
               return;
           }
           $that.attr({'full':false,'title':'全屏'}).html('<i class="layui-icon layui-icon-screen-full"></i>');
       }
    });
    $("#onlyImp").click(function () {
        document.getElementById("closeAllTabs").click();
        setTimeout(function () {$('#infoArea').removeClass('layui-show')},100);
        loadMenu("imp");
    });
    $("#onlyExp").click(function () {
        document.getElementById("closeAllTabs").click();
        setTimeout(function () {$('#infoArea').removeClass('layui-show')},100);
        loadMenu("exp");
    });
    $("#everySee").click(function () {
        setTimeout(function () {$('#infoArea').removeClass('layui-show')},100);
        loadMenu();
    });
    var $menuCloseBtn = $('.menu-btn')
    ,$menuOpenBtn = $('.menu-btn-open')
    ,$menuWrapper = $('#menuWrapper')
    ,$zmBody = $('.zm-body')
    ,$zmContent = $('.zm-tab-content');

    $menuCloseBtn.click(function () {
        $menuCloseBtn.hide();
        $menuWrapper.animate({width:'0px'});
        $zmBody.animate({left:'10px'});
        $zmContent.animate({left:'11px'},function () {
            $menuOpenBtn.show();
        });
    });
    $menuOpenBtn.click(function () {
        $menuOpenBtn.hide();
        $zmBody.animate({left:'180px'});
        $zmContent.animate({left:'181px'});
        $menuWrapper.animate({width:'160px'},function () {
            $menuCloseBtn.show();
        });
    });

    $('#closeThisTabs').click(function () {
        setTimeout(function () {$('#closeArea').removeClass('layui-show')},100);
        closeTab(getLocalStorage('op_menu_id'),'');
    });
    $('#closeOtherTabs').click(function () {
        setTimeout(function () {$('#closeArea').removeClass('layui-show')},100);
        var outLayId = getLocalStorage('op_menu_id');
        $('.zm-tab-title').find('li[lay-id]').each(function (i,o) {
            var $that = $(o),layId=$that.attr('lay-id');
            if(layId!='0'&&layId!=outLayId){
                closeTab(layId,'');
            }
        });
    });
    $('#closeAllTabs').click(function () {
        setTimeout(function () {$('#closeArea').removeClass('layui-show')},100);
        $('.zm-tab-title').find('li[lay-id]').each(function (i,o) {
            var $that = $(o),layId=$that.attr('lay-id');
            if(layId!='0'){
                closeTab(layId,'');
            }
        });
    });

    // $.post(rurl('scm/subject/version'),{},function (res) {
    //     if(isSuccess(res)){
    //         var data = res.data;
    //         $('.info-domain').html(data.domain);
    //         $('.open-version').html(data.openVersionDesc);
    //         $('.staff-number').html(data.staffNumber);
    //         $('.invalid-time').html(data.invalidTime);
    //         $('#staffPerson').attr({'lay-percent':data.useNumber+'/'+data.staffNumber});
    //         element.render('progress', 'staff-person');
    //     }
    // });
});
function closeTab(mid,msg) {
    layui.element.tabDelete('pageTab', mid);
    if(!isEmpty(msg)){prompt_error(msg);}
}
function initUser() {
    var user = app.obtainUser();
    $('.p-name').html(user.personName);
}
function obtainMIdByOperation(operation) {
    var $menu = $('a[operation-code="'+operation+'"]');
    if($menu.length>0){return $menu.attr('menu-id');}
    return '';
}
function updatePassword(){openwin(rurl('/user/update-pwd.html'),'修改登录密码',{area: ['620px', '300px']});}
var taskListWin=null,rightTips=null;
function showTaskList(){
    layer.close(taskListWin);
    layer.close(rightTips);
    taskListWin = openwin('task/list.html','待处理任务',{resize:false,shadeClose:true,anim:0,area: ['800px', '320px'],offset:['60px',($(window).width()-810)+'px']});
}
function showDislikeTaskList() {
    openwin('task/dislike.html','已忽略的任务通知',{shadeClose:true,anim:0,area: ['600px', '400px']});
}
function refreshTab(mid){
    closeTab(mid);
    $('a[menu-id="'+mid+'"]').click();
}
function connectionSocket() {
    try{
        var token = getLocalStorage('TSF_SCM');
        if(isEmpty(token)){return;}
        var host = location.host;
        var protocol = location.protocol;
        var ws;
        if(protocol.indexOf("https") != -1){
            ws = new WebSocket("wss://"+ location.host+"/websocket?token=" + token);
            //ws = new WebSocket("ws://"+location.host+"/websocket?token=" + token);
        } else {
            ws = new WebSocket("ws://"+location.host+"/websocket?token=" + token);
        }
        ws.onopen = function(){console.log("建立连接....")};
        ws.onmessage = function(evt) {
            console.log("收到消息....");
            newTask();
        }
        ws.onclose = function() {
            console.log("连接关闭....");
            setTimeout(function(){connectionSocket();},10000);
        }
    }catch (e) {
        setTimeout(function(){connectionSocket();},10000);
    }
    //获取新任务
    newTask();
}
var $twinkle = $('#twinkle');
function newTask() {
    $.post(rurl('scm/taskNotice/count'),{},function (res) {
        if((res.data || 0)>0){
            $twinkle.html(res.data<100?res.data:99).show();
        }else{
            $twinkle.html('').hide();
        }
    });
}
function showRightTips(res) {
    layer.close(rightTips);
    if(res.count>0){
        var data = res.data[0];
        rightTips = layer.open({
            title:data.operationName,type: 1,offset: 'rb',shade: 0,anim: 2,zIndex:999999,
            content: ['<div class="layui-row p10"><a href="javascript:" id="executeOutTask">',
                data.content,
                '</a><div class="layui-row mt10 mb10 t-a-r">',
                (res.count>1)?'<a href="javascript:" onclick="showTaskList();" class="text-grey">查看全部（'+res.count+'）</a>':'',
                '</div></div>'].join(''),
            success:function () {
                $('#executeOutTask').bind('click',function(){
                    layer.close(rightTips);
                    var actionParams = JSON.parse(data['actionParams']),
                        taskArg={"documentId":data.documentId,"documentClass":data.documentType,"operation":data.operationCode};
                    setLocalStorage('TASK_'+actionParams['pmid'],data['queryParams']);
                    setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
                    refreshTab(actionParams['pmid']);
                });
            }
        });
    }
}

function loadMenu(sectionModule) {
    var requestUrl = isEmpty(sectionModule) ? 'scm/menu/userBgMenus' : 'scm/menu/userBgMenusSection';
    var data = {};
    if(isNotEmpty(sectionModule)) {
        data = {'sectionModule':sectionModule};
    }
    $.get(rurl(requestUrl),data,function (res) {
        if(isSuccess(res)){
            var data = res.data,mhtml = [],menusObj = {};
            if(data.length==0){
                prompt_warn('对不起您无任何操作权限，请联系贵司管理员授权');
                return;
            }
            $.each(data,function (i,o) {
                mhtml.push('<li class="layui-nav-item '+((i==0)?'layui-nav-itemed':'')+'">');
                mhtml.push('<a href="javascript:">'+(isEmpty(o.icon)?'':'<i class="'+o.icon+'"></i>')+' '+o.name+'</a>');
                mhtml.push('<dl class="layui-nav-child">');
                if(o.childs&&o.childs.length>0){
                    $.each(o.childs,function (j,k) {
                        mhtml.push('<dd><a href="javascript:" menu-id="'+k.id+'" '+(isEmpty(k.operationCode)?'':' operation-code="'+k.operationCode+'" ')+'>'+k.name+'</a></dd>');
                        menusObj[k.id] = k;
                    });
                }
                mhtml.push('</dl></li>');
            });
            $('#menu').html(mhtml.join(''));
            layui.element.init();
            $('a[menu-id]').click(function () {
                var $that = $(this),omenu = menusObj[$that.attr('menu-id')];
                if($('li[lay-id="'+omenu.id+'"]').size()==0){
                    var url = rurl(omenu.url+((omenu.url.indexOf("?")!=-1)?'&':'?')+'mid='+omenu.id);
                    layui.element.tabAdd('pageTab', {id:omenu.id, title: omenu.name,content: '<iframe src="'+url+'" name="'+omenu.id+'"></iframe>'})
                }
                layui.element.tabChange('pageTab', omenu.id);
            });
            layui.element.on('tab(pageTab)', function(){
                var layId = this.getAttribute('lay-id'),$lmenu = $('a[menu-id="'+layId+'"]');
                $('a[menu-id]').removeClass('active');
                $lmenu.addClass('active');
                var pmenu = $lmenu.parent().parent().parent();
                if(!pmenu.hasClass('layui-nav-itemed')){
                    pmenu.addClass('layui-nav-itemed');
                }
                setLocalStorage('op_menu_id',layId);
            });
            //打开上次进入的页面
            var defMenuId = getLocalStorage('op_menu_id');
            if(!isEmpty(defMenuId)){
                $('a[menu-id="'+defMenuId+'"]').click();
            }
        }
    });
}